package com.csx.framework.springboot.sample.event;

import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 *
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/2/27 周二 16:28
 */
@Component
@EnableAsync
public class CustomAnnotationEventListener {

    // 使用 @EventListener标注方法为监听器,参数类型为事件类型
    @EventListener
    public void onApplicationEvent(CustomApplicationEvent event) {
        System.out.println("CustomAnnotationEventListener 接收到 CustomApplicationEvent 类型的事件,事件信息: " + event.getSource());
    }

    @EventListener
    public void onApplicationEvent(PayloadApplicationEvent payloadApplicationEvent) {
        System.out.println("CustomAnnotationEventListener 接收到 【" +payloadApplicationEvent.getResolvableType() + "】 类型的事件，事件信息: " + payloadApplicationEvent.getPayload());
    }

    /**
     * 标注了 @Async 注解的方法会被异步线程执行
     * @param event
     * @throws InterruptedException
     */
    @Order(1)
    @EventListener
    @Async
    public void onApplicationEventAsync1(CustomApplicationEvent event) throws InterruptedException {
        Date start = new Date();
        Thread.sleep(2000);
        System.out.printf("线程:[%s],监听器1,接收时间:[%s],处理完成时间:[%s],接收到事件:%s\n", Thread.currentThread().getName(), start, new Date(), event.getSource());

    }

    @Order(2)
    @EventListener
    public void onApplicationEventAsync2(CustomApplicationEvent event) throws InterruptedException {
        Date start = new Date();
        Thread.sleep(2000);
        System.out.printf("线程:[%s],监听器2,接收时间:[%s],处理完成时间:[%s],接收到事件:%s\n", Thread.currentThread().getName(), start, new Date(), event.getSource());

    }
}
